import './CalendarStyle_2.css';
import React from 'react';
import { Icon , Popover} from 'antd';
import { isEqual } from 'lodash';
import { formatDate, _str2Int } from '../../../../util/common';
import { weeklyCalendar } from '../../weeklyCalendar.js';
import { WeaErrorPage, WeaTools, WeaNewScroll, WeaLocaleProvider } from 'ecCom';
import { getLunarDatas } from '../../util.js';
const getLabel = WeaLocaleProvider.getLabel;
const { ls } = WeaTools;
// 视图切换-红色风格
class CalendarStyle_2 extends React.Component {
	constructor(props) {
        super(props);
        let _date = new Date();
        this.state = {
            weaWorkplanLoaded: false,
            refresh: false,
            data: props.data,
            workplanData: [],
            createVisible: false,
            createType: 'create',
            workPlanId: '',
            currentDate: formatDate(_date, 'yyyy-MM-dd'),
            currentMonth: formatDate(_date, 'yyyy-MM'),
            activeKey: '1',
            defaultView:props.defaultView=='0'?'2':props.defaultView||'2',
            weekstartday: 0,
            isShowLunar: props.isShowLunar,
            monthSel:false,
            curY:parseInt(formatDate(_date, 'yyyy')),
        };
        this.doAdd = this.doAdd.bind(this);
        this.onClose = this.onClose.bind(this);
        this.getWorkplanData = this.getWorkplanData.bind(this);
        this.onCaleViewTypeChange = this.onCaleViewTypeChange.bind(this);
        this.onClickData = this.onClickData.bind(this);
        this.onVisibleChange = this.onVisibleChange.bind(this);
        this.choseMonth = this.choseMonth.bind(this);
    }

    componentWillMount() {
        // 异步加载日程模块静态资源
        eventRegister.loadModule('f_workplan', () => {
            this.setState({ weaWorkplanLoaded: true });
        }, () => {});
    }

	componentDidMount() {
        WeaTools.callApi('/api/workplan/calendar/getBaseData', 'POST').then((data) => {
            this.setState({
                weekstartday: data.weekstartday,
            });
            this.onCaleViewTypeChange(this.state.isShowLunar,this.state.defaultView);  
        });
        this.getWorkplanData(new Date(), this.state.defaultView);// 获取data  events
    }

    onCaleViewTypeChange(isShowLunar,defaultViewvalue,date) {
        const { eid } = this.props;
        const {  weekstartday, currentDate } = this.state;
        this.setState({ defaultView: defaultViewvalue});
        // $(`#e9PortalSetting #calendar_${eid} #portal_weeklyCalendar`).length==1 元素设置页
        weeklyCalendar($(`#e9PortalSetting #calendar_${eid} #portal_weeklyCalendar`).length == 1 ? `#e9PortalSetting #calendar_${eid} #portal_weeklyCalendar` : `#calendar_${eid} #portal_weeklyCalendar`, {
            getDateType: defaultViewvalue, // 1日/2周/3月/4双周
            getWeekstartday: weekstartday, // 周一开始还是周末开始
            defaultDate: date==undefined?currentDate:date, // 设置默认选中日期
            getisShowLunarDatas: isShowLunar, // 是否显示农历 1显示，0不显示
            geteid: eid, // 当前元素eid
            // 获取选中日期
            getSelectedDate(dateTime) {

            },
            getWorkplanData: this.getWorkplanData,
            onCaleViewTypeChange:this.onCaleViewTypeChange,
             // 点击日期回调
            clickDate(dateTime) {
                let clickd=dateTime.split('-');
                this.getWorkplanData(dateTime, '1');
                let clicky=parseInt(clickd[0]);
                let clickm=parseInt(clickd[1]);
                let nowy=parseInt($(`#calendar_${eid} #portal_weeklyCalendar #curyear_selector`).html());
                let nowm=parseInt($(`#calendar_${eid} #portal_weeklyCalendar #curmonth_selector`).html());
                if(clicky!=nowy||clickm!=nowm){
                    this.onCaleViewTypeChange(isShowLunar,defaultViewvalue,dateTime)
                } 
            },
             // 点击切换箭头回调
            clickPreNextDate(dateTime, datatype) {
                this.getWorkplanData(dateTime, datatype);
                this.getWorkplanData(dateTime, 1);
            },
        });
        this.getWorkplanData(date==undefined?this.state.currentDate:date, defaultViewvalue);
        this.getWorkplanData(date==undefined?this.state.currentDate:date, 1);
    }

    componentWillReceiveProps(nextProps) {
        if (!isEqual(this.props, nextProps)) {
            this.getWorkplanData(new Date(), '1');
            this.setState({ isShowLunar: nextProps.isShowLunar ,  defaultView:nextProps.defaultView==undefined?(this.props.defaultView=='0'?'2':this.props.defaultView||'2'):(nextProps.defaultView=='0'?'2':nextProps.defaultView||'2')});
            this.onCaleViewTypeChange(nextProps.isShowLunar, nextProps.defaultView==undefined?this.props.defaultView:nextProps.defaultView);
        }
    }

    getWorkplanData(currentDate, caleViewType) {
        const { eid } = this.props;
	    let viewType = '1';
        viewType = caleViewType;
        WeaTools.callApi('/api/workplan/calendar/MyCalendar', 'POST', { viewType, selectDate: formatDate(new Date(currentDate), 'yyyy-MM-dd') }).then((data) => {
            this.setState({
                currentDate,
            });
            if(parseInt(caleViewType)==1){
                this.setState({
                    data
                });
            }
            let dateStr = '';
            $(`#calendar_${eid} #portal_weeklyCalendar #weeklyCanlendarBox li a`).each(function () {
                dateStr = $(this).attr('data-time');

                data.events.map((arr) => {
                    let startDate = formatDate(new Date(arr[2]), 'yyyy-MM-dd');
                    let endDate = formatDate(new Date(arr[3]), 'yyyy-MM-dd');
                    
                    if (dateStr >= startDate && dateStr <= endDate) {
                        $(this).removeClass('Canlendar_hasEvent');
                        $(this).addClass('Canlendar_hasEvent');
                    }
                });
            });
        });
    }
    onVisibleChange(visible) {this.setState({monthSel:visible})}

    choseMonth(num,ind){
        const { eid } = this.props; 
        const {curY}=this.state;  
        let nowY=curY+num;
        var nowy=parseInt(formatDate(new Date(), 'yyyy'))
        var nowm=parseInt(formatDate(new Date(), 'MM'))
        var nowd=parseInt(formatDate(new Date(), 'dd'))
        this.setState({curY:nowY})
        if(!isNaN(ind)){
            let curm=ind+1;
            let dateTime= nowy==nowY&&curm==nowm ? nowy+'-'+curm+'-'+nowd : nowY+'-'+curm+'-01';
            this.onCaleViewTypeChange(this.state.isShowLunar,this.state.defaultView,dateTime)    
        }
    }

	render() {
		const { eid, layoutid, isShowLunarDatas = '0' } = this.props;
		let className = '';
		if (isShowLunarDatas == '1') {
		    className = 'calendar_Lunar';
        }
        const { weaWorkplanLoaded, isShowLunar, createVisible, createType, currentDate, workPlanId, activeKey, data, defaultView ,monthSel, curY } = this.state;
        let createConditionParams = ['', '', currentDate, formatDate(new Date(), 'hh:mm'), currentDate, '23:59', '0'];
        let weeks =[`${getLabel(527999, '星期日')}`, `${getLabel(528000, '星期一')}`, `${getLabel(528001, '星期二')}`, `${getLabel(528002, '星期三')}`, `${getLabel(528003, '星期四')}`, `${getLabel(528004, '星期五')}`, `${getLabel(528005, '星期六')}`]
        let weekIndex = new Date(currentDate).getDay();  
        let week = weeks[weekIndex];  

        const date = new Date(currentDate).getDate();
        const lunarDateTime = getLunarDatas().toLunar(formatDate(new Date(currentDate), 'yyyy'), formatDate(new Date(currentDate), 'M'), formatDate(new Date(currentDate), 'd'))
        const lunarDate = lunarDateTime.lunarDay
        const lunarMonth = lunarDateTime.lunarMonth
        const lunarYear = lunarDateTime.lunarYear
        const zodiac = getLunarDatas().zodiacYear(lunarDateTime.lyCopy) 
        let MonthArr=[getLabel(528177, '1月'),getLabel(528178, '2月'),getLabel(528179, '3月'),getLabel(528180, '4月'),
        getLabel(528181, '5月'),getLabel(528182, '6月'),getLabel(528183, '7月'),getLabel(528184, '8月'),
        getLabel(528185, '9月'),getLabel(528186, '10月'),getLabel(528187, '11月'),getLabel(528188, '12月')];
        let curM=parseInt(formatDate(new Date(currentDate), 'MM'))-1;
        let todayM=parseInt(formatDate(new Date(), 'MM'))-1;
		return (<div id={`calendar_${eid}`} className={`${className} Cus_portalCanlendar Cus_portalCanlendar2`}>
            <div id="portal_weeklyCalendar" className="portalWeeklyCanlendar portalweekly_style2">
            <div className="dateTime">
                  <div className="left">
                    <div className="solar">
                      <div className="week wea-f14">{week}</div>
                      <div className="date">{date}<div className="iconper"></div></div>
                    </div>
                  </div>
                  <div className="line"></div>
                  <div className="right">
                    <div className="lunar">
                      <div className="month-date">{lunarMonth}月{lunarDate}</div>
                        <div className="year">{lunarYear}年【{zodiac}年】</div>
                    </div>
                    
                  </div>
                  </div>
                <div className="week_head">
                    <div className="viewtype_tab">
                        <div className={`single_week ${defaultView == '2' ? 'select_viewtype' : ''}`} onClick={() => { this.onCaleViewTypeChange(isShowLunar, '2'); }}>{getLabel(523941, '周')}</div>
                        <div className={`double_week ${defaultView == '4' ? 'select_viewtype' : ''}`} onClick={() => { this.onCaleViewTypeChange(isShowLunar, '4'); }}>{getLabel(523942, '双周')}</div>
                        <div className={`month_type  ${defaultView == '3' ? 'select_viewtype' : ''}`} onClick={() => { this.onCaleViewTypeChange(isShowLunar, '3'); }}>{getLabel(523943, '月')}</div>
                    </div>
                    <div className="viewtype_changemonth datetime_header  wea-f14">
                        <a href="javascript:;" title={getLabel(528322, '上一周')} className="prev_icon" role="prev_week"><i className="icon-coms-Browse-box-delete" /></a>
                        <Popover
                            trigger="click"
                            placement="bottomRight"
                            content={
                                <div className='weeksel-container'>
                                    <div className='year-sel'>
                                        <div className='prev-year'  onClick={() => {this.choseMonth(-1); }}><i className="icon-coms-Left" /></div>
                                        <div className='yearselected'>{curY}</div>
                                        <div className='next-year'  onClick={() => {this.choseMonth(1); }}><i className="icon-coms-Right" /></div>
                                        </div>
                                    <div className='month-sel'>
                                        {
                                            MonthArr.map((item,index)=>{
                                                let clasname='month-item';
                                                if(curM==index&&todayM==index){clasname='month-item month-itemsel month-itemtoday';}
                                                else if(curM==index&&todayM!=index){clasname='month-item month-itemsel';}
                                                else if(curM!=index&&todayM==index){clasname='month-item month-itemtoday';}
                                                return(<div className='month-single'>
                                                    <div className={clasname} title={item} onClick={() => { this.onVisibleChange(false);this.choseMonth(0,index); }}>{item}</div>
                                                </div>)
                                            })
                                        }
                                    </div>
                                </div>      
                            }
                            overlayClassName="Cus_portalCanlendar_overlay"
                            visible={monthSel}
                            onVisibleChange={this.onVisibleChange}
                        >
                            <span className='showChangeMonth' onClick={()=>{
                                this.setState({curY:parseInt($(`#calendar_${eid} #portal_weeklyCalendar #curyear_selector`).html())})
                            }}><b role="year_selector" id="curyear_selector" />{getLabel(523944, '年')}<b role="month_selector" id="curmonth_selector" />{getLabel(523943, '月')}<b role="week_selector" /></span>
                        </Popover> 
                        <a href="javascript:;" title={getLabel(528323, '下一周')}  className="next_icon" role="next_week"><i className="icon-coms-Browse-box-Add-to" /></a>
                    </div>
                </div>
                <div style={{clear:'both'}}/>
                {/* 周 */}
                <ul role="weeks_ch" className="weeklyBox" />
                {/* 日历展示区 */}
                <ul role="weeklyCanlendarView" className="weeklyCanlendarBox" id="weeklyCanlendarBox" />
                {
                    defaultView == '2' || defaultView == '4' ?
                    <div className="week_showdown" onClick={() => { this.onCaleViewTypeChange(isShowLunar, '3'); }}><i className="icon-coms-down" /></div>
                    : null
                }
            </div>
            <CalendarData data={data} eid={eid} currentDate={currentDate} handleClick={this.onClickData} />
            <div className="portal-element-calender-add2">
                <Icon type="plus-circle-o" title={getLabel(611, '添加')} onClick={this.doAdd} />
            </div>
            {weaWorkplanLoaded && window.weaWorkplan && window.weaWorkplan.com ? <window.weaWorkplan.com.WorkPlanCreate
              isCustom={parseInt(layoutid) > 5}
              type={createType}// 新建为'create',查看为'preview',编辑edit,共享share
              visible={createVisible}// 显隐受控
              doClose={this.onClose}// 关闭回调
              onlyClose={() => this.setState({ createVisible: false, activeKey: '1' })}// 关闭回调
              workPlanId={workPlanId} // 日程id，查看日程时用到
              createConditionParams={createConditionParams}// 创建的默认值日期和时间,没有传[]
              activeKey={activeKey} // 查看页面显示的面板1是基本信息，7是相关交流
              changeTab={value => this.setState({ activeKey: value })}// 查看页面切换面板的回调
              selectUser={''}
            /> : ''}
		</div>);
    }
    doAdd() {
        this.setState({
            createVisible: true,
            createType: 'create',
        });
    }
    onClose() {
        this.setState({
            createVisible: false,
            activeKey: '1',
        });
        this.getWorkplanData(this.state.currentDate, this.state.defaultView);
        this.getWorkplanData(this.state.currentDate, 1);
    }
    onClickData(id) {
        this.setState({
            createVisible: true,
            createType: 'preview',
            workPlanId: id,
        });
    }
}


class MyErrorHandler extends React.Component {
	render() {
		const hasErrorMsg = this.props.error && this.props.error !== '';
		return (
			<WeaErrorPage msg={hasErrorMsg ? this.props.error : getLabel(385218, '对不起，该页面异常，请联系管理员！')} />
		);
	}
}
CalendarStyle_2 = WeaTools.tryCatch(React, MyErrorHandler, { error: '' })(CalendarStyle_2);
export default CalendarStyle_2;

class CalendarData extends React.Component {
    tc(d) {
        function zc(c, i) {
            let d = '666666888888aaaaaabbbbbbdddddda32929cc3333d96666e69999f0c2c2b1365fdd4477e67399eea2bbf5c7d67a367a994499b373b3cca2cce1c7e15229a36633cc8c66d9b399e6d1c2f029527a336699668cb399b3ccc2d1e12952a33366cc668cd999b3e6c2d1f01b887a22aa9959bfb391d5ccbde6e128754e32926265ad8999c9b1c2dfd00d78131096184cb05288cb8cb8e0ba52880066aa008cbf40b3d580d1e6b388880eaaaa11bfbf4dd5d588e6e6b8ab8b00d6ae00e0c240ebd780f3e7b3be6d00ee8800f2a640f7c480fadcb3b1440edd5511e6804deeaa88f5ccb8865a5aa87070be9494d4b8b8e5d4d47057708c6d8ca992a9c6b6c6ddd3dd4e5d6c6274878997a5b1bac3d0d6db5a69867083a894a2beb8c1d4d4dae54a716c5c8d8785aaa5aec6c3cedddb6e6e41898951a7a77dc4c4a8dcdccb8d6f47b08b59c4a883d8c5ace7dcce';
            return `#${d.substring(c * 30 + i * 6, c * 30 + (i + 1) * 6)}`;
        }
        let c = d != null && d != undefined ? d : option.theme;
        return [zc(c, 0), zc(c, 1), zc(c, 2), zc(c, 3)];
    }
    render() {
        const { currentDate, handleClick, eid, data } = this.props;
        let index = 0;
        let color = '#a32929';
        let _currentDate = formatDate(new Date(currentDate), 'yyyy-MM-dd');
        if(data&&data.events&&data.events.length){
            let html = data.events.map((arr) => {
                if (arr[7]) color = arr[7];
                let startStr = formatDate(new Date(arr[2]), 'yyyy-MM-dd');
                let endStr = formatDate(new Date(arr[3]), 'yyyy-MM-dd');
                let id = arr[0];
                let name = arr[1];
                let stime = startStr < _currentDate ? '00:00' : formatDate(new Date(arr[2]), 'hh:mm');// 开始时间
                let ss = '';
                let etime = _currentDate<endStr? '23:59' : formatDate(new Date(arr[3]), 'hh:mm');;// 结束时间
                let ess = '';
                if (!isNaN(parseInt(stime))) {
                    ss = parseInt(stime) >= 12 ? 'pm' : 'am';
                }
                if (!isNaN(parseInt(etime))) {
                    ess = parseInt(etime) >= 12 ? 'pm' : 'am';
                }
                if (_currentDate >= startStr && _currentDate <= endStr) {
                    index += 1;
                    return (<div className="hand dataEvent"
                      style={{ height: '30px' }}
                      onClick={handleClick.bind(this, id)}
                      title={name}
                    >
                            <div className="dataEvent1"  />
                            <div className="cus_dataEvent2">
                                <div className="dataEvent2_1">
                                    {stime}-{etime}
                                </div>
                            </div>
                            <div className="dataEvent3">{name}</div>
                        </div>);
                    }
                });

                let height = index * 46-16;
                if ( index < 3) {
                    return (<div id={`calendar_content${eid}`}>
                        <div id="planDataEvent"
                          className="planDataEvent planDataEvent2"
                          style={{ height, overflowY: 'hidden', outline: 'none' }}
                        >
                            <div id="planDataEventchd" style={{ height }}>
                                {html}
                            </div>
                        </div>
                    </div>);
                }
                return (<WeaNewScroll scrollId="element_calendar_scroll" height={138}>
                    <div id={`calendar_content${eid}`}>
                        <div id="planDataEvent"
                          className="planDataEvent planDataEvent2"
                          style={{ height, overflowY: 'hidden', outline: 'none' }}
                        >
                            <div id="planDataEventchd" style={{ height }}>
                                {html}
                            </div>
                        </div>
                    </div>
                </WeaNewScroll>);
        }
        return <div className='portal_weeklyCalendar_nodata'>
        <img className='portal_weekimg' src='/spa/portal/images/CalendarStyle/nodata2.png'/>
        <div className='portal_weektips'>{getLabel(524328, '暂无日程')}</div>
    </div>;
    }
}
